package com.canxi.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.canxi.common.annotation.Log;
import com.canxi.common.annotation.RepeatSubmit;
import com.canxi.common.core.controller.BaseController;
import com.canxi.common.core.domain.PageQuery;
import com.canxi.common.core.domain.R;
import com.canxi.common.core.page.TableDataInfo;
import com.canxi.common.core.validate.AddGroup;
import com.canxi.common.core.validate.EditGroup;
import com.canxi.common.enums.BusinessType;
import com.canxi.common.exception.ServiceException;
import com.canxi.common.helper.LoginHelper;
import com.canxi.common.utils.poi.ExcelUtil;
import com.canxi.user.domain.bo.CxUserBo;
import com.canxi.user.domain.vo.CxUserVo;
import com.canxi.user.service.IUserService;
import com.canxi.system.domain.vo.SysOssVo;
import com.canxi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 *
 * @author ruoyi
 * @date 2022-10-22
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/user/user")
public class UserController extends BaseController {

    private final IUserService iUserService;

    private final ISysOssService iSysOssService;
    /**
     * 查询用户信息列表
     */
    @SaCheckPermission("user:user:list")
    @GetMapping("/list")
    public TableDataInfo<CxUserVo> list(CxUserBo bo, PageQuery pageQuery) {
        return iUserService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出用户信息列表
     */
    @SaCheckPermission("user:user:export")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CxUserBo bo, HttpServletResponse response) {
        List<CxUserVo> list = iUserService.queryList(bo);
        ExcelUtil.exportExcel(list, "用户信息", CxUserVo.class, response);
    }

    /**
     * 获取用户信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("user:user:query")
    @GetMapping("/{id}")
    public R<CxUserVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return R.ok(iUserService.queryById(id));
    }

    @GetMapping("/currentUser")
    public R<CxUserVo> getCurrentInfo() {
        return R.ok(iUserService.queryById(String.valueOf(LoginHelper.getLoginUser().getUserId())));
    }

    @GetMapping("/getUser")
    public R<CxUserVo> getUser(CxUserBo bo) {
        return R.ok(iUserService.queryById(String.valueOf(LoginHelper.getLoginUser().getUserId())));
    }

    /**
     * 新增用户信息
     */
    @SaCheckPermission("user:user:add")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CxUserBo bo) {
        return toAjax(iUserService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改用户信息
     */
    @SaCheckPermission("user:user:edit")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CxUserBo bo) {
        return toAjax(iUserService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除用户信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("user:user:remove")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iUserService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @SaCheckPermission("user:user:reset")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @DeleteMapping("/resetPassword/{id}")
    public R<Void> resetPassword(@NotEmpty(message = "主键不能为空")
                          @PathVariable String id) {
        return toAjax(iUserService.resetPasswordById(id));
    }

/**
 * 上传图片
 */
//@SaIgnore
//@PostMapping("/upload")
//public R<Map> uploadFile(MultipartFile file) throws Exception
//{
//    try
//    {
////        // 上传文件路径
////        String filePath = CXConfig.getUploadPath();
////        // 上传并返回新文件名称
////        String fileName = FileUploadUtils.upload(filePath, file);
////        String url = ServerConfig.getUrl() + fileName;
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("url", url);
//        map.put("fileName", fileName);
//        map.put("newFileName", FileUtils.getName(fileName));
//        map.put("originalFilename", file.getOriginalFilename());
//        return R.ok(map);
//    }
//    catch (Exception e)
//    {
//        return R.fail(e.getMessage());
//    }
//}

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @SaIgnore
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/uploadOss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> uploadOss(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

}
